package com.guoranhao.admin.web.utils;


import com.guoranhao.admin.constants.ApiConstants;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Description: 获取请求真实IP地址
 * All Rights Reserved.
 * @version 1.0  2016年10月20日 下午12:08:53  by 代鹏（daipeng.456@gmail.com）创建
 */
public class IpUtil {

	public static final String getRealIp(HttpServletRequest request) {
		String ip = request.getHeader(ApiConstants.X_FORWARDED_FOR);
		if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
			if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader(ApiConstants.PROXY_CLIENT_IP);
			}
			if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader(ApiConstants.WL_PROXY_CLIENT_IP);
			}
			if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader(ApiConstants.HTTP_CLIENT_IP);
			}
			if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getHeader(ApiConstants.HTTP_X_FORWARDED_FOR);
			}
			if (StringUtils.isEmpty(ip) || ApiConstants.UNKNOWN.equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!(ApiConstants.UNKNOWN.equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}

}
